package com.xky.example_student.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xky.example_student.entity.Permission;
import com.xky.example_student.mapper.PermissionMapper;
import com.xky.example_student.service.PermissionService;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {

    @Override
    public Map<String, Boolean> getAllPermissions() {
        List<Permission> permissions = this.list();
        Map<String, Boolean> permissionMap = new HashMap<>();
        
        for (Permission permission : permissions) {
            permissionMap.put(permission.getPermissionKey(), permission.getPermissionValue());
        }
        
        return permissionMap;
    }

    @Override
    public boolean updatePermission(String key, Boolean value) {
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("permission_key", key);
        
        Permission permission = this.getOne(queryWrapper);
        if (permission == null) {
            return false;
        }
        
        permission.setPermissionValue(value);
        permission.setUpdateTime(new Date());
        return this.updateById(permission);
    }

    @Override
    public void initializeDefaultPermissions() {
        // 默认权限配置
        Map<String, String> defaultPermissions = new HashMap<>();
        defaultPermissions.put("studentEdit", "允许学生修改个人信息");
        defaultPermissions.put("studentScore", "允许学生查看成绩");
        defaultPermissions.put("teacherEdit", "允许教师修改个人信息");
        defaultPermissions.put("teacherScore", "允许教师修改学生成绩");
        defaultPermissions.put("teacherAdmin", "允许教师使用管理员功能");
        
        for (Map.Entry<String, String> entry : defaultPermissions.entrySet()) {
            QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("permission_key", entry.getKey());
            
            if (this.count(queryWrapper) == 0) {
                Permission permission = new Permission();
                permission.setPermissionKey(entry.getKey());
                permission.setPermissionValue(true);  // 默认启用所有权限
                permission.setDescription(entry.getValue());
                permission.setUpdateTime(new Date());
                this.save(permission);
            }
        }
    }
}
